import datetime
from types import new_class

import django
from numpy import insert
from dvadmin.utils.get_accessToken import DingtalkHelper
from dvadmin.system.models import Dept,Role,Users,CeleryLog,CeleryResLog
from django.db import transaction
from django.db.models.signals import post_save
from django.dispatch import Signal,receiver
from dvadmin.utils.json_response import ErrorResponse
from django.contrib.auth.hashers import make_password
from conf.env import DEFAULT_PASSWORD
from dvadmin.utils.string_util import random_str

async_signal = Signal()
dingObject = DingtalkHelper()

@transaction.atomic
def async_dept(ins_obj):
    try:
        dingding_dept_data = dingObject.get_deptList()
        dept_data = Dept.objects.values_list('dept_id',flat=True)
        dept_count = Dept.objects.count()
        new_sort = 1
        if dept_count>0:
            for k in dingding_dept_data:
                new_sort =new_sort+1
                if k.get('dept_id') in dept_data:
                    Dept.objects.filter(dept_id=k.get('dept_id')).update(name=k.get('name'),parent_id=k.get('parent_id'))
                else:
                    Dept.objects.create(dept_id=k.get('dept_id'),name=k.get('name'),modifier=1,sort=new_sort,dept_belong_id=1,creator_id=1,parent_id=k.get('parent_id'))
        else:
            for k in dingding_dept_data:
                new_sort =new_sort+1
                Dept.objects.create(dept_id=k.get('dept_id'),name=k.get('name'),modifier=1,sort=new_sort,dept_belong_id=1,creator_id=1,parent_id=k.get('parent_id'))    
        CeleryResLog.objects.create(result_type=1,celery_res_id=ins_obj.id,return_data='同步成功',modifier=1,dept_belong_id=1,creator_id=1)
    except Exception as e: 
        CeleryResLog.objects.create(result_type=2,celery_res_id=ins_obj.id,return_data=e.args,modifier=1,dept_belong_id=1,creator_id=1)
         

@transaction.atomic
def async_role(ins_obj):
    try:
        dingding_role_data = dingObject.get_roleList()
        role_data = Role.objects.values_list('role_id',flat=True)
        role_count = Role.objects.count()
        new_sort=1
        if role_count>0:
            for i in dingding_role_data['list']:
                for k in i.get('roles'):
                    new_sort =new_sort+1
                    if k.get('id') in role_data:
                        Role.objects.filter(role_id=k.get('id')).update(name=k.get('name'))
                    else:
                        Role.objects.create(role_id=k.get('id'),name=k.get('name'),sort=new_sort,key=k.get('id'),modifier=1,dept_belong_id=1,creator_id=1)
        else:
            for i in dingding_role_data['list']:
                new_sort =new_sort+1
                for k in i.get('roles'):
                    Role.objects.create(role_id=k.get('id'),sort=new_sort,name=k.get('name'),key=k.get('id'),modifier=1,dept_belong_id=1,creator_id=1)
        CeleryResLog.objects.create(result_type=1,celery_res_id=ins_obj.id,return_data='同步成功',modifier=1,dept_belong_id=1,creator_id=1)
    except Exception as e:
        CeleryResLog.objects.create(result_type=2,celery_res_id=ins_obj.id,return_data=e.args,modifier=1,dept_belong_id=1,creator_id=1)
        return ErrorResponse(code=4000,msg='同步角色失败')

@transaction.atomic
def async_user(ins_obj):
    try:
        deptId_data = Dept.objects.values_list('dept_id',flat=True)
        for i in deptId_data:
            userId_data = Users.objects.values_list('users_id',flat=True)
            dingding_user_data = dingObject.get_usersListByDept(deptId=i)
            for k in dingding_user_data['list']:
                if k.get('userid') in userId_data: # 如果已存在，则进行更新
                    userInfo_data = dingObject.get_usersInfoByUserId(UserId=k.get('userid'))
                    up_obj=Users.objects.get(users_id=k.get('userid'))
                    up_obj.name=k.get('name')
                    up_obj.email=k.get('email')
                    up_obj.mobile=k.get('mobile')
                    up_obj.avatar=k.get('avatar')
                    d_obj=Dept.objects.get(dept_id=k.get('dept_id_list')[0])
                    up_obj.dept_id=d_obj.id
                    arr = []    
                    if userInfo_data.get('role_list') is None:
                        up_obj.role.clear()
                    else:
                        up_obj.role.clear()
                        for p in userInfo_data.get('role_list'):
                            arr.append(p.get('id'))
                        role_user = Role.objects.filter(role_id__in=arr)
                        if len(role_user)!=None:
                            up_obj.role.add(*role_user)
                    up_obj.save()
                else:
                    userInfo_data = dingObject.get_usersInfoByUserId(UserId=k.get('userid'))
                    cr_obj=Users.objects.create(users_id=k.get('userid'),password=make_password(DEFAULT_PASSWORD),name=k.get('name'),username=random_str(),email=k.get('email'),
                    mobile=k.get('mobile'),avatar=k.get('avatar'),modifier=1,dept_belong_id=1,creator_id=1)
                    d_obj=Dept.objects.get(dept_id=k.get('dept_id_list')[0])
                    cr_obj.dept_id=d_obj.id
                    arr = []
                    if userInfo_data.get('role_list') is None:
                        cr_obj.role.clear()
                    else:
                        for p in userInfo_data.get('role_list'):
                            arr.append(p.get('id'))
                        role_user = Role.objects.filter(role_id__in=arr)
                        if len(role_user)!=None:
                            cr_obj.role.add(*role_user)
                    cr_obj.save()
        CeleryResLog.objects.create(result_type=1,celery_res_id=ins_obj.id,return_data='同步成功',modifier=1,dept_belong_id=1,creator_id=1)
    except Exception as e:
        CeleryResLog.objects.create(result_type=2,celery_res_id=ins_obj.id,return_data=e.args,modifier=1,dept_belong_id=1,creator_id=1)
        return ErrorResponse(code=4000,msg='同步员工失败')


# 这里当接收到CeleryLog保存数据时，获得信号
@receiver(post_save,sender=CeleryLog)
def pre_save_func(sender,instance, **kwargs):
    # time_obj = datetime.datetime.strptime(str(instance.work_time), "%Y-%m-%d %H:%M:%S")
    if instance.async_type==1: # 同步部门
        async_dept(ins_obj=instance)
    elif instance.async_type==2: # 同步角色
        async_role(ins_obj=instance)
    elif instance.async_type==3: #同步人员
        async_user(ins_obj=instance) 
